<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/2
 * Time: 10:44
 */

namespace app\api\controller;

use app\common\model\Bankroll;
use app\common\model\MoneyDetail;
use think\Db;
use think\Exception;

/**
 * 资金管理
 */
class Money extends  User
{
    /**
     * 资金明细接口
     */
    public function detail()
    {
        $data = input('post.');

        $where['user_id'] = $this->user_id;
        $where['status'] = 1;

        if ($data['month']){

            $info = date_parse_from_format('Y-m', $data['month']);

            $check =  0 == $info['warning_count'] && 0 == $info['error_count'];

            if ($check){

                $where['create_time'] = ['between time',getMonthRange($data['month'])];

            }else{

                api_return(0,'时间格式错误');

            }

        }

        if(is_numeric($data['type'])){
            $where['type'] = $data['type'];
        }

        $model = new MoneyDetail();

        $rows  = $model->getList($where);

        api_return(1,'获取成功',$rows);
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 用户充值提现明细
     */
    public function roll()
    {
        $data = input('post.');

        $where['user_id'] = $this->user_id;

        if ($data['month']){

            $info = date_parse_from_format('Y-m', $data['month']);

            $check =  0 == $info['warning_count'] && 0 == $info['error_count'];

            if ($check){

                $where['create_time'] = ['between time',getMonthRange($data['month'])];

            }else{

                api_return(0,'时间格式错误');

            }

        }

        if(is_numeric($data['type'])){

            $where['type'] = $data['type'];

        }

        $model = new Bankroll();

        $rows = $model->getRows($where);

        api_return(1,'获取成功',$rows);

    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 提现界面
     */
    public function cashView()
    {
        $data['balance'] = $this->userBalance();

        $null = [
            'account_id' => '',
            'type' => '',
            'status' => '',
            'account' => '',
        ];

        $data['tips'] = self::getExplain('cashView');
        $data['editTips'] = self::getExplain('editAccount');
        $data['cash_view'] = $this->extend('cash_view');

        $map['user_id'] = $this->user_id;
        $map['type'] = 1;
        $data['card'] = Db::name('user_account')->field('account_id,type,status,account')->where($map)->find()??$null;
        $map['type'] = 2;
        $data['alipay'] = Db::name('user_account')->field('account_id,type,status,account')->where($map)->find()??$null;

        api_return(1,'获取成功',$data);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 提现申请
     */
    public function cash()
    {
        $this->ApiLimit(3,$this->user_id);

        $data = request()->only(['money','account_id']);

        $ID = $this->userInfo('ID');

        if (!is_numeric($ID)){
            api_return(0,'未实名认证不能提现');
        }

        $cash['user_id'] = $this->user_id;
        $cash['status']  = 2;
        $cash['type']    = 2;

        $b_id = Db::name('bankroll')->where($cash)->value('b_id');

        if ($b_id) api_return(0,'您有提现申请正在审核中,请等待审核成功后重试');

        $money = Db::name('extend')->where('id',1)->value('money');
        $highest = $this->extend('highest_money');
        if (!is_numeric($data['money']) || $data['money'] < $money ) api_return(0,'提现魅力值为'.$money.'起');
        if ($data['money'] > $highest ) api_return(0,'提现魅力值最高为'.$highest);

        $map['user_id']    = $this->user_id;
        $map['account_id'] = $data['account_id'];
        $map['status']     = 1;

        $account = Db::name('user_account')->where($map)->find();

        if (!$account) api_return(0,'账号不存在或审核未通过');

        if ($data['money'] > $this->userBalance()['cash']) api_return(0,'账户可提现钻石不足');

        $cashRatio = self::getExplain('cashRatio');

        if ($cashRatio >= 100 || $cashRatio == 0){
            api_return(0,'系统手续费扣除错误,请稍后重试');
        }

        $ratio = bcdiv($cashRatio,100,2);

        //提现手续费
        $charge = bcmul($ratio,$data['money'],2);
        //总计扣除金额
        $total = $data['money'] + $charge;

        if ($total > $this->userBalance()['cash']) api_return(0,'账户余额不够扣除'.$cashRatio.'%的手续费');

        $data['user_id'] = $this->user_id;
        $data['status']  = 2;
        $data['type']    = 2;
        $data['remark']  = '提现'.$data['money'].'钻(手续费'.$charge.'钻('.$cashRatio.'%))';
        $data['create_time'] = time();
        $data['ratio_money'] = $charge;
        $data['ratio'] = $cashRatio;

        switch ($account['type']){
            case 1:
                $data['trade_type'] = 4;
                break;
            case 2:
                $data['trade_type'] = 5;
                break;
            default:
                api_return(0,'提现账户信息错误');
        }

        Db::startTrans();
        try{
            Db::name('users')->where('user_id',$this->user_id)->setDec('cash',$total);
            Db::name('bankroll')->insert($data);
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            api_return(0,'系统错误',$e->getMessage());
        }
        $this->destroyLimit($this->user_id);

        api_return(1,'提交成功');

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 购买贵族
     */
    public function buyNoble()
    {
        $this->ApiLimit(2,$this->user_id);

        $data = $this->noblePrice($this->user_id);
        $update['noble_id']   = $data['noble_id'];
        $update['noble_time'] = $data['noble_time'];
        $price = $data['price'];

        $give  = $data['give'];
        if ($price <= 0) api_return(0,'价格错误');
        Db::startTrans();
        try{
            //钻石支付
            $this->moneyDec($price);
            //加上赠送金额
            Db::name('users')->where('user_id',$this->user_id)->setInc('money',$give);
            money_detail(1,$this->user_id, '贵族('.$data['noble_name'].')购买赠送',$give,'赠送');

            //增加经验
            $this->addLevel($price,$this->user_id);
            //更新贵族信息
            Db::name('user_extend')->where('user_id',$this->user_id)->update($update);

            money_detail(2,$this->user_id, '贵族('.$data['noble_name'].')购买',$price,'消费');

            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            api_return(0,'服务器繁忙,请稍后重试',$e->getMessage());
        }
        $str = $data['noble_name'].'开通成功,本次购买赠送了'.$price.'点经验和'.$give.'钻石';
        self::sendUsrMsg('system',hashid($this->user_id),$str);

        $this->destroyLimit($this->user_id);
        api_return(1,'购买成功');

    }




}